package com.codegenerate.demo.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codegenerate.demo.config.R;
import com.codegenerate.demo.dto.LoginDto;
import com.codegenerate.demo.dto.SysAccountDto;
import com.codegenerate.demo.entity.SysAccount;
import com.codegenerate.demo.service.AuthService;
import com.codegenerate.demo.service.SysAccountService;
import com.codegenerate.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service("AuthService")
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisTemplate<String, Serializable> serializableRedisTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysAccountService accountService;

    /**
     * 输入token 内存获取 token
     * @param token
     * @return
     */
    @Override
    public R<SysAccount> parseToken(String token) {
        var accountId=(String) (redisTemplate.opsForValue().get("token_"+token));
        var user = accountService.getById(accountId);
        return R.ok(user);
    }


    /**
     * 登录
     * @return
     */
    @Override
    public R<LoginDto> login(LoginDto loginDto) {
         // region 查看用户 是否存在
                var query=new QueryWrapper<SysAccount>().lambda();
                query.eq(SysAccount::getUserName, loginDto.getUserName());
                var pagheresult=accountService.page(new Page<>(1, 1), query);
                if(pagheresult.getRecords().size()<=0){
                 return R.failed(StringUtils.format("没有 {}的用户", loginDto.getUserName()));
                }
         // endregion
        // region  判断账号密码时候 一致
        query.eq(SysAccount::getPassWord, loginDto.getPassWord());
        var pagheresult2=accountService.page(new Page<>(1, 1), query);
        if(pagheresult2.getRecords().size()<=0){
            return R.failed(StringUtils.format("账号{}密码 不一致", loginDto.getUserName()));
        }
        // endregion
        // region  得到随机的token 存到内存中
        var currentUser=pagheresult2.getRecords().stream().findFirst();
        if(currentUser.isEmpty()){
            return R.failed("用户密码不一致");
    }
        var  token= IdUtil.simpleUUID();
        redisTemplate.opsForValue().set("token_" + token, ""+currentUser.get().getId());
        loginDto.setToken(token);
        // endregion


        return R.ok(loginDto);
    }


}
